const app = getApp();
var openid = wx.getStorageSync('openid');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    curNav: 3,
    page:1,
    cateList: [],
    petsList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.request({
      url: app.config.serverCfg.domain.cate,
      data: {
        page: that.data.page,
        size: '20'
      },
      success(res) {
        that.setData({
          cateList: res.data.data,
        });
        that.getPetsList(res.data.data[0]['id']);
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.loadMore();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /* 把点击到的某一项 设为当前curNav   */
  switchRightTab: function (e) {
    let id = e.target.dataset.id;
    this.setData({
      curNav: id,
      page:1,
    })
    this.getPetsList(id);
    //回到顶部
    wx.pageScrollTo({
      scrollTop: 0
    })
  },
  /**进入文章详情 */
  getDetail: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: 'detail/detail?id=' + id,
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', {
        })
      }
    })
  },
  getPetsList: function (id) {
    var that = this;
    wx.request({
      url: app.config.serverCfg.domain.topic,
      data: {
        page: '1',
        size: '20',
        id: id
      },
      success(res) {
        that.setData({
          petsList: res.data.data,
        });
      }
    })
  },
  /*加载更多*/
  loadMore() {
    var that = this;
    wx.showNavigationBarLoading();
    wx.request({
      url: app.config.serverCfg.domain.topic,
      method: 'post',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: {
        openid: openid,
        id: that.data.curNav,
        page: ++that.data.page,
      },
      success: function (res) {
        if (res.data.data.length == 0) {
          wx.showToast({
            title: '已经加载完毕',
            icon: 'none',
            duration: 2000
          })
          wx.hideNavigationBarLoading();
          return false;
        }
        that.data.petsList = that.data.petsList.concat(res.data.data);
        wx.hideNavigationBarLoading();
        that.setData({
          petsList: that.data.petsList,
        })
      }
    });
  },
})